<?php 

class FRM_Tools_Validation
{

	protected $model;

	protected $rules;

	protected $field;

	protected $value;

	protected $id;

	protected $fieldId;
	
	protected $extra;
	
	protected $op;

	/**
	 * load the uri
	 *
	 */
	public function __construct($model, $rules)
	{
		$this->model = $model;
		$this->rules = $rules;
	}

	public function validateField($field, $value, $id=0, $fieldId='id', $extra='', $op='or'){

		$this->field = $field;
		$this->value = $value;
		$this->id = $id;
		$this->fieldId = $fieldId;
		$this->extra = $extra;
		$this->op = $op;
		
		if(!empty($this->rules[$field])){
			$r = $this->rules[$field];
			if(!is_array($r)){
				$r = array($r);
			}

			foreach ($r as $v)
			{
				$v = $v.'Field';
				if(method_exists($this, $v)){
					$r = $this->$v();
					if($r){
						return array('success'=>true, 'valid'=>false, "reason"=>$r);
					}
				}
			}

		}
		
		return array('success'=>true, 'valid'=>true, "reason"=>'');
	}


	private function uniqueField(){
		
		$extra = ($this->extra)?" {$this->op} ".$this->extra:'';
		
		$where = $this->field . " LIKE '{$this->value}'";
		if($this->id){
			$where .= " AND (". $this->fieldId . " != '{$this->id}' $extra)";
		}
		//print $where;
		$rows = $this->model->fetchAll($where);

		if(!is_null($rows) && $rows->count() > 0)
		{
			return 'Такоe поле уже используется.';
		}
		return false;
	}
}